import axios from "axios";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const fetch = require("node-fetch");
function axiosSever(url: string, method: string, data?: IAnyObject): Promise<IAnyObject> {
  return new Promise<IAnyObject>((resolve, reject) => {
    if (method === 'GET') {
      axios.get(url)
        .then((response: any) => {
          resolve(response.data.data);
        })
        .catch((error) => reject(error))
    } else if (method === 'POST') {
      fetch("https://sctapi.ftqq.com/sso/check", {
          "headers": {
            "accept": "application/json, text/plain, */*",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
            "pragma": "no-cache",
            "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"101\", \"Google Chrome\";v=\"101\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site"
          },
          "referrer": "https://sct.ftqq.com/",
          "referrerPolicy": "strict-origin-when-cross-origin",
          "body": `token=${data.token}`,
          "method": "POST",
          "mode": "cors",
          "credentials": "omit"
        }).then((response: IAnyObject) => response.json())
        .then((json: IAnyObject) => {
          resolve(json);
        })
        .catch((error: any) => console.log('Request Failed', error)); 
    } 
  })
}

function sendMsg(item: IAnyObject) {
  fetch(`https://sctapi.ftqq.com/${item.sendkey}.send`, {
    "headers": {
      "accept": "application/json, text/plain, */*",
      "accept-language": "zh-CN,zh;q=0.9",
      "cache-control": "no-cache",
      "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
      "pragma": "no-cache",
      "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"101\", \"Google Chrome\";v=\"101\"",
      "sec-ch-ua-mobile": "?0",
      "sec-ch-ua-platform": "\"Windows\"",
      "sec-fetch-dest": "empty",
      "sec-fetch-mode": "cors",
      "sec-fetch-site": "same-site",
      "Referer": "https://sct.ftqq.com/",
      "Referrer-Policy": "strict-origin-when-cross-origin"
    },
    "body": `title=${encodeURI(item.title)}&desp=${encodeURI(item.detail)}`,
    "method": "POST"
  }).then((response: IAnyObject) => response.json())
  .then((json: IAnyObject) => {
    console.log(json);
  });
  // axios.post(`https://sctapi.ftqq.com/${item.sendkey}.send`, {
  //   title: item.title,
  //   desp: item.detail,
  //   channel: 9,
  // },
  // {
  //   headers: {
  //     'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
  //   },
  // }
  // )
  //   .then((response: IAnyObject) => {
  //     console.log(response, '发送成功')
  //   })
  //   .catch((error) => {
  //     console.log('Request Failed', error)
  //   })
}


// 每天定时给雨晨发消息
const sendYCMessageOnce = () => {
  const item = {
    title: '学习强国',
    detail: '看学习强国了捏雨晨',
    sendkey: 'SCT151939TNlaqzYWHwiQyVKpTxW9CBzJC',
  };

  sendMsg(item);
}

const sendYCMessageTwice = () => {
  const item = {
    title: '学习强国',
    detail: '看学习强国了捏雨晨',
    sendkey: 'SCT151939TNlaqzYWHwiQyVKpTxW9CBzJC',
  };

  sendMsg(item);
}

const store = {} as any;
export const sendInfo = () => {
  setInterval(() => {
    for (const item of Object.keys(store)) {
      if (Math.abs(Date.now() - Number(item)) <= 1000 * 60) {
        console.log('发消息了', item, store[item]);
        sendMsg(store[item]);
        delete store[item];
      }
    }
  }, 10000)

  // 每天定时发送消息
  setInterval(() => {
    const refreshHours = new Date().getHours();
    const refreshMin = new Date().getMinutes();
    if((refreshHours === 21 || refreshHours === 20) && refreshMin === 1){
        // 指定每天凌晨做的事情
        sendYCMessageTwice();
    }

  }, 1000 * 60);
}

// sendInfo();

export async function getCode(ctx: Context, next: Next): Promise<void> {
  try {
    const result = await axiosSever('https://sctapi.ftqq.com/user/signin', 'GET');
    ctx.api.success(result, 'sucess');
  } catch (err) {
    ctx.api.fail(-1, '获取二维码接口失败，请重试');
  }
  
  return next();
}

export async function addMsg(ctx: Context, next: Next): Promise<void> {
  const { body } = ctx.request;
  const { time, title, detail, sendkey } = body;
  try {
    store[time] = {
      title,
      detail,
      sendkey,
    }
    ctx.api.success({}, 'sucess');
  } catch (err) {
    ctx.api.fail(-1, '失败');
  }
  
  return next();
}

export async function check(ctx: Context, next: Next): Promise<void> {
  const query = ctx.request.query;
  try {
    const data = {
      token: query.token,
    }
    const result = await axiosSever('', 'POST', data);
    ctx.api.success(result, 'sucess');
  } catch (err) {
    ctx.api.fail(-1, err);
  }
  
  return next();
}